********************************************************************************
**	PURPOSE: Create rest of response letter tables (3-6)	 
**							
**	INPUTS: Long with outcomes.dta
**	
**	OUTPUTS: Credit Behaviors_post_avg effects_flag_randomized_rt2.xls - Not used
**			 Credit Behaviors_post_het groups_flag_randomized_rt2.xls - Not used
**			 Credit Behaviors_post_avg effects 1218_flag_randomzied_rt2.xls - Not used
**			 Credit Behaviors_post_het groups 1218_flag_randomized_rt2.xls - Not used
**			 Credit Behaviors_post_avg effects_flag_randomized_c6.xls - Response Letter Table 3
**			 Credit Behaviors_post_het groups_flag_randomized_c6.xls - Response Letter Table 3
**			 Credit Behaviors_post_avg effects_flag_randomized_c7.xls - Response Letter Table 3
**			 Credit Behaviors_post_het groups_flag_randomized_c7.xls - Response Letter Table 3 
**			 HET effects by OI2.xls - Response Letter Table 4
**			 HET effects by OI2 pval.xls - Response Letter Table 4
**			 
**			 
**  CREATED/MODIFIED BY: Leah Kim
**
**	DATE CREATED: 
**
**	DATE LAST EDITED: 4/11/2022
********************************************************************************

clear 

/*******************************************************************************
1. Respose Letter 3 
********************************************************************************/

*A. Filename and table title
local filename1  "Credit Behaviors_post_het groups"
local filename1a "Credit Behaviors_post_avg effects"
local filename1c "Credit Behaviors_post_het groups 1218"
local filename1ac "Credit Behaviors_post_avg effects 1218"

*B. Define the covariate regression spec options and the outcome variables of interest
local outcomes  z_inquiry12 z_numaccts //outcomes 
local decs 3		//decimals 
local lowter ltca	//lower tercile of installment credit activity at baseline index
local midter mtca	//middle tercile of installment credit activity at baseline index 
local highter htca	//upper tercile of installment credit activity at baseline index

//Spec for average treatment effects 
	* By post 
		local loanspec1a post 1.enc#1.post	
//Spec for heterogeneous treatment effect by post 
	* By post 
		local loanspec1h 1.`lowter'#1.post 1.`midter'#1.post 1.`highter'#1.post 1.`lowter'#1.enc#1.post 1.`midter'#1.enc#1.post 1.`highter'#1.enc#1.post 

forval i = 1/2 {		
		
* Import data
use "$adta/Long with outcomes.dta", clear

if `i' == 2 {
	loc s "c"
	drop if index == 6
	local outcomes z_newcredit_i `outcomes' z_default_index_all_i
}

* Regression loop with output 
	loc j 1 
	local wordcount = 1
	foreach regvar in `outcomes' {
		foreach restrict in "flag_randomized"  {
			cap drop __*
			local wordtot : word count `outcomes'
			areg `regvar' `loanspec`j'a' if `restrict' == 1 /* & `=cond("`wordcount'" == "`wordtot'", "op18", "`restrict'")' == 1 */, absorb(surveyid) vce(cluster surveyid)
			local inds = e(df_a) + 1
			local obs = e(N)
			sum `regvar' if e(sample) == 1 & post == 1 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_post = string(abs(r(mean)), "%14.`decs'f") 
			}  //end if 
			else {
				local mu_lhs_post = string(r(mean), "%14.`decs'f") 
			}           
			sum `regvar' if e(sample) == 1 & index == 6 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_6 = string(abs(r(mean)), "%14.`decs'f") 
			 }  //end if 
			else {
				local mu_lhs_6 = string(r(mean), "%14.`decs'f") 
			} 
			sum `regvar' if e(sample) == 1 & index == 12 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_12 = string(abs(r(mean)), "%14.`decs'f") 
			}  //end if 
			else {
				local mu_lhs_12 = string(r(mean), "%14.`decs'f") 
			} 
			sum `regvar' if e(sample) == 1 & index == 18 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_18 = string(abs(r(mean)), "%14.`decs'f") 
			}  //end if 
			else {
				local mu_lhs_18 = string(r(mean), "%14.`decs'f") 
			}        
			sum `regvar' if e(sample) == 1 & index == 1 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs = string(abs(r(mean)), "%14.`decs'f") 
			} 	//end if 
			else {
				local mu_lhs = string(r(mean), "%14.`decs'f") 
			}                     
			if "`regvar'" == "`: word 1 of `outcomes''" {
				local action = "replace"
			}   //end regvar ==
			else {
				local action = "append"
			}       
			#delimit ;                              
			outreg2 using "$outputtables/`filename`j'a`s''_`restrict'_rt2.xls", `action' excel label
				nocons noobs dec(`decs') nor2 addtext(Obs, `obs', Individuals, `inds', 
				Mean Dependent Variable in Extra Step Group at Baseline, `mu_lhs', 
				Mean Dep Var In Extra Step at Post, `mu_lhs_post', 
				Mean Dep Var In Extra Step at 6, `mu_lhs_6', 
				Mean Dep Var In Extra Step at 12, `mu_lhs_12', 
				Mean Dep Var In Extra Step at 18, `mu_lhs_18')  
				slow(8000) nonote noaster;
			#delimit cr;
			sleep 2000 
			cap drop __*
	
			areg `regvar' `loanspec`j'h' if `restrict' == 1 /* & `=cond("`wordcount'" == "`wordtot'", "op18", "`restrict'")' == 1 */ , absorb(surveyid) vce(cluster surveyid)
			local obs = e(N)
			local inds = e(df_a) + 1
			sum `regvar' if e(sample) == 1 & index == 1 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs = string(abs(r(mean)), "%14.`decs'f") 
			} 	 //end if 
			else {
				local mu_lhs = string(r(mean), "%14.`decs'f") 
			}  // end else
			if `j' == 1 {
				test 1.`lowter'#1.enc#1.post = 1.`midter'#1.enc#1.post
				local pvalue1_2 = string(r(p), "%14.`decs'f")
				test 1.`midter'#1.enc#1.post = 1.`highter'#1.enc#1.post
				local pvalue2_3 = string(r(p), "%14.`decs'f")
				test 1.`lowter'#1.enc#1.post = 1.`highter'#1.enc#1.post
				local pvalue1_3 = string(r(p), "%14.`decs'f")
				
				if "`regvar'" == "`: word 1 of `outcomes''" {
					local action = "replace"
				} 	 //end regvar == 
				else {
					local action = "append"
				}  	//end else  
				
				#delimit ;                              
				outreg2 using "$outputtables/`filename`j'`s''_`restrict'_rt2.xls", `action' excel label 
					nocons noobs dec(`decs') nor2 
					addtext(P-value of 1.`lowter'#1.enc#1.post = 1.`midter'#1.enc#1.post, `pvalue1_2',
							P-value of 1.`midter'#1.enc#1.post = 1.`highter'#1.enc#1.post, `pvalue2_3', 
							P-value of 1.`lowter'#1.enc#1.post = 1.`highter'#1.enc#1.post, `pvalue1_3',
							Obs, `obs', Individuals, `inds', Mean Dependent Variable in Extra Step Group at Baseline, `mu_lhs')  
					slow(8000) nonote noaster;
				#delimit cr;
				sleep 2000 
				//output a blank column
				outreg2 using "$outputtables/`filename`j'`s''_`restrict'_rt2.xls", append skip
			}  //end j == 1
		}	//end restrict
		local ++wordcount
	} //ends regvar
}
	
* Column 6 ---------------------------------------------------------------------

*A. Import data
use "$adta/Long with outcomes.dta", clear
tab cm_delinquent op18, missing
tab cm_delinquent_rc op18, missing 
tab cm_delinquent cm_delinquent_rc, missing 
replace cm_delinquent = cm_delinquent_rc // -- change from 07 Heterogeneity driven by credit behaviors

local decs 3

*B. Baseline means 
sum cm_delinquent if enc==0 & flag_randomized==1 & index==1
local bd_flag_randomized = string(r(mean), "%14.`decs'f") 
sum cm_delinquent if enc==0 & flag_randomized_scored_base==1 & index==1
local bd_flag_randomized_scored_base = string(r(mean), "%14.`decs'f") 
* Post means 
sum cm_delinquent if enc==0 & flag_randomized==1 & post==1
local pd_flag_randomized = string(r(mean), "%14.`decs'f") 
sum cm_delinquent if enc==0 & flag_randomized_scored_base==1  & post==1
local pd_flag_randomized_scored_base = string(r(mean), "%14.`decs'f") 
	
*C. Panel A 

* Regressions 
drop if index==1
foreach restrict in "flag_randomized" "flag_randomized_scored_base" {
	cap drop __*
	reg cm_delinquent enc if `restrict'==1, vce(cluster surveyid)
	local inds = e(df_r) + 1
	local obs = e(N)
	#de ; 
	outreg2 using "$outputtables/Credit Behaviors_post_avg effects_`restrict'_c6.xls", replace
		keep(enc) label nocons noobs dec(`decs') nor2 addtext(Obs, `obs', Individuals, `inds',
		Mean Dep Var In Extra Step at Post, `pd_`restrict'') slow(8000) nonote noaster ; 
	#de cr 
}	
				
*D. Panel B : Het groups  
local lowter ltca	//lower tercile of installment credit activity at baseline index
local midter mtca	//middle tercile of installment credit activity at baseline index 
local highter htca	//upper tercile of installment credit activity at baseline index

*E. Regressions 
drop if index==1
foreach restrict in "flag_randomized" "flag_randomized_scored_base" {
	cap drop __*
	reg cm_delinquent 1.`lowter'#1.enc 1.`midter'#1.enc 1.`highter'#1.enc if `restrict'==1, vce(cluster surveyid)
	local inds = e(df_r) + 1
	local obs = e(N)
	test 1.`lowter'#1.enc = 1.`midter'#1.enc
	local pvalue1_2 = string(r(p), "%14.`decs'f")
	test 1.`midter'#1.enc = 1.`highter'#1.enc
	local pvalue2_3 = string(r(p), "%14.`decs'f")
	test 1.`lowter'#1.enc = 1.`highter'#1.enc
	local pvalue1_3 = string(r(p), "%14.`decs'f")
	#d ; 
	outreg2 using "$outputtables/Credit Behaviors_post_het groups_`restrict'_c6.xls", replace
		keep(1.`lowter'#1.enc 1.`midter'#1.enc 1.`highter'#1.enc) label nocons noobs dec(`decs') nor2 
		addtext(Obs, `obs', Individuals, `inds', 
		Mean Dependent Variable in Extra Step Group at Baseline, "NA",
		P-value of 1.`lowter'#1.enc = 1.`midter'#1.enc, `pvalue1_2', 
		P-value of 1.`midter'#1.enc = 1.`highter'#1.enc, `pvalue2_3', 
		P-value of 1.`lowter'#1.enc = 1.`highter'#1.enc, `pvalue1_3') slow(8000) nonote noaster ; 
	#d cr 
}	


* Column 7 ---------------------------------------------------------------------

**NOTE: Use this specification for column 7 of table six, but first collapse so that there is only one observation per person
*first have to replace cases where people didn't take up CBL with zeros
*A. Import data
use "$adta/Long with outcomes.dta", clear
local decs 3

tab cm_delinquent cm_delinquent_rc, missing
mdesc cm_delinquent_rc if index == 1 // 1917 missing
mdesc cm_delinquent_rc if index == 6 // +6 missing 
mdesc cm_delinquent_rc if index == 12 // +12 missing
mdesc cm_delinquent_rc if index == 18  // +19 missing

gen miss_delinquent = missing(cm_delinquent_rc) if op18 == 1
egen nummiss_delinquent = total(miss_delinquent), by(surveyid)

*egen evermiss_delinquent = max(miss_delinquent) if op18 == 1, by(surveyid)
egen num_delinquent = total(cm_delinquent_rc), by(surveyid)
*distinct surveyid if evermiss_delinquent == 1 & num_delinquent == 0 

*replace cm30plus_rc = . if evermiss_delinquent == 1 & num_delinquent == 0 & op18 == 1 // ever delinquent turned to missing for surveyids with only 0s and missings in CBL_delinquent == 1

replace cm30plus_rc = . if nummiss_delinquent == 3

tab cm30plus_rc if op18 == 0 // every delinquent is missing for any non_CBL takers

***check number of observations***
distinct surveyid if flag_randomized == 1 & inlist(index,6,12,18) & op18 == 1 // 320
assert r(ndistinct) == 320
distinct surveyid if ~missing(cm_delinquent_rc) & flag_randomized == 1 & inlist(index,6,12,18) // 314
assert r(ndistinct) == 314
*egen check = total(miss_delinquent) if num_delinquent == 0 & flag_randomized == 1 & inlist(index,6,12,18) & op18 == 1, by(surveyid)
*distinct surveyid if check == 3 // 6(1531-1525), all missing for endline 6, 12 and 18 month endline
*assert r(ndistinct) == 6
distinct surveyid if ~missing(cm30plus_rc) & flag_randomized == 1 & inlist(index,6,12,18) // 314
assert r(ndistinct) == 314
*distinct surveyid if check > 0 & ~missing(check) // 16(1531-1515), all missing for endline 6, 12 and 18 month endline
*assert r(ndistinct) == 16 

replace cm30plus = cm30plus_rc 

*B. Collapse 
collapse (max) cm30plus enc flag_randomized flag_randomized_scored_base pt1 pt2 pt3 op18 ltca mtca htca, by(surveyid)
distinct surveyid if ~missing(cm30plus) & flag_randomized == 1

reg cm30plus enc if flag_randomized == 1, vce(cluster surveyid)		//this is the correct one
//reg cm30plus enc if flag_randomized == 1 & op18==1, vce(cluster surveyid) //this corresponds to column 7 in the old table--TOT rather than ITT 

*C. Get post means 
sum cm30plus if enc==0 & flag_randomized==1
local b3_flag_randomized = string(r(mean), "%14.`decs'f") 
sum cm30plus if enc==0 & flag_randomized_scored_base==1
local b3_flag_randomized_scored_base = string(r(mean), "%14.`decs'f") 
	
*D. Regressions 
foreach restrict in "flag_randomized" "flag_randomized_scored_base" {
	cap drop __*
	reg cm30plus enc if `restrict'==1, vce(cluster surveyid)
	local inds = e(df_r) + 1
	local obs = e(N)
	#de ; 
	outreg2 using "$outputtables/Credit Behaviors_post_avg effects_`restrict'_c7.xls", replace
		keep(enc) label nocons noobs dec(`decs') nor2 addtext(Obs, `obs', Individuals, `inds',
		Mean Dep Var In Extra Step at Post, `b3_`restrict'') slow(8000) nonote noaster ; 
	#de cr 
}	
				
*E. Panel B : Het groups  
local lowter ltca	//lower tercile of installment credit activity at baseline index
local midter mtca	//middle tercile of installment credit activity at baseline index 
local highter htca	//upper tercile of installment credit activity at baseline index

*F. Regressions 
foreach restrict in "flag_randomized" "flag_randomized_scored_base" {
	cap drop __*
	reg cm30plus 1.`lowter'#1.enc 1.`midter'#1.enc 1.`highter'#1.enc if `restrict'==1, vce(cluster surveyid)
	local inds = e(df_r) + 1
	local obs = e(N)
	test 1.`lowter'#1.enc = 1.`midter'#1.enc
	local pvalue1_2 = string(r(p), "%14.`decs'f")
	test 1.`midter'#1.enc = 1.`highter'#1.enc
	local pvalue2_3 = string(r(p), "%14.`decs'f")
	test 1.`lowter'#1.enc = 1.`highter'#1.enc
	local pvalue1_3 = string(r(p), "%14.`decs'f")
	#d ; 
	outreg2 using "$outputtables/Credit Behaviors_post_het groups_`restrict'_c7.xls", replace
		keep(1.`lowter'#1.enc 1.`midter'#1.enc 1.`highter'#1.enc) label nocons noobs dec(`decs') nor2 
		addtext(Obs, `obs', Individuals, `inds', 
		Mean Dependent Variable in Extra Step Group at Baseline, "NA", 
		P-value of 1.`lowter'#1.enc = 1.`midter'#1.enc, `pvalue1_2', 
		P-value of 1.`midter'#1.enc = 1.`highter'#1.enc, `pvalue2_3', 
		P-value of 1.`lowter'#1.enc = 1.`highter'#1.enc, `pvalue1_3') slow(8000) nonote noaster ; 
	#d cr 
}	

/*******************************************************************************
2. Respose Letter 4
********************************************************************************/

use "$adta/Long with outcomes.dta", clear
sort surveyid index
gen noopeninstallB1 = ~ openinstallB1
replace noopeninstallB1 = . if missing(openinstallB1)

*Previous loans, smaller than 1, larger than 1
gen prevloans1_s1_1 = (prevloans <= 1) if index == 1 & ~missing(prevloans) 
egen prevloans1_s1 = max(prevloans1_s1_1), by(surveyid) 
drop prevloans1_s1_1
gen prevloans1_l1 = ~prevloans1_s1 if ~missing(prevloans1_s1)
tab prevloans1_s1 // approx 25%
tab prevloans1_l1 // approx 75%

*Have account with major derogatory events
gen numacctsderog1_1_1 =  (numacctsderog ~= 0) if index == 1 & ~missing(numacctsderog)
egen numacctsderog1_1 = max(numacctsderog1_1_1), by(surveyid)
drop numacctsderog1_1_1
gen numacctsderog1_0 = ~numacctsderog1_1 if ~missing(numacctsderog1_1)
tab numacctsderog1_0 numacctsderog1_1 

loc outcomes ficoscore08

loc spec 1.post#1.openinstallB1 1.post#1.noopeninstallB1 1.enc#1.post#1.openinstallB1 1.enc#1.post#1.noopeninstallB1

loc sample1 numacctsderog1_1 
loc sample2 numacctsderog1_0
loc sample3 prevloans1_s1
loc sample4 prevloans1_l1

est clear
loc m 1 
foreach var of local outcomes { 
  forvalues t = 1/4 {
		fvset base none surveyid
  		reg `var' `spec' i.surveyid if `=cond("`var'" == "ficoscore08", "flag_randomized_scored_base", "flag_randomized")'  == 1 & `sample`t''== 1
		est store `var'`t'_compare
		areg `var' `spec' if `=cond("`var'" == "ficoscore08", "flag_randomized_scored_base", "flag_randomized")'  == 1 & `sample`t''== 1, absorb(surveyid) vce(cluster surveyid) 
		est store `var'`t'
		
		loc obs = e(N)
		loc inds = e(df_a) + 1
		sum `var' if index == 1 & enc == 0 & `sample`t'' == 1
		loc mean_extra : di %6.3f `r(mean)'
		
		outreg2 using "$outputtables/HET effects by OI2.xls", excel label nocons noobs dec(3) nor2 slow(8000) nonote noaster addtext( Observations, `obs', Individuals, `inds', Mean dependent variable in Extra Step Group at baseline, `mean_extra') `=cond(`m' == 1,"replace","append")'		
		local ++m
  }
}

mat pval = J(2,2,.)

suest ficoscore081_compare ficoscore082_compare, vce(cluster surveyid)
test [ficoscore081_compare_mean]1.enc#1.post#1.openinstallB1 = [ficoscore082_compare_mean]1.enc#1.post#1.openinstallB1
mat pval[1,1] = r(p)
test [ficoscore081_compare_mean]1.enc#1.post#1.noopeninstallB1 = [ficoscore082_compare_mean]1.enc#1.post#1.noopeninstallB1
mat pval[2,1] = r(p)

suest ficoscore083_compare ficoscore084_compare, vce(cluster surveyid)
test [ficoscore083_compare_mean]1.enc#1.post#1.openinstallB1 = [ficoscore084_compare_mean]1.enc#1.post#1.openinstallB1
mat pval[1,2] = r(p)
test [ficoscore083_compare_mean]1.enc#1.post#1.noopeninstallB1 = [ficoscore084_compare_mean]1.enc#1.post#1.noopeninstallB1
mat pval[2,2] = r(p)

putexcel set "$outputtables/HET effects by OI2 pval.xls.xls", replace
putexcel A1 = matrix(pval), nformat(number_d2)

/*******************************************************************************
3. Response Letter 5
********************************************************************************/
*A. Filename and table title
local filename1  "open revolving het"
local filename1a "open revolving avg"

*B. Define the covariate regression spec options and the outcome variables of interest
local outcomes  openrevolvtr //outcomes 
local decs 3		//decimals 
local lowter ltca	//lower tercile of installment credit activity at baseline index
local midter mtca	//middle tercile of installment credit activity at baseline index 
local highter htca	//upper tercile of installment credit activity at baseline index

//Spec for average treatment effects 
	* By post 
		local loanspec1a post 1.enc#1.post	
	* By endline
		local loanspec2a pt1 pt2 pt3 1.enc#1.pt1 1.enc#1.pt2 1.enc#1.pt3

//Spec for heterogeneous treatment effect by post 
	* By post 
		local loanspec1h 1.`lowter'#1.post 1.`midter'#1.post 1.`highter'#1.post 1.`lowter'#1.enc#1.post 1.`midter'#1.enc#1.post 1.`highter'#1.enc#1.post //PL: new
	* By endline 
		local loanspec2h pt1 pt2 pt3 1.`lowter'#1.pt1 1.`lowter'#1.pt2 1.`lowter'#1.pt3 1.`lowter'#1.enc#1.pt1 1.`lowter'#1.enc#1.pt2 1.`lowter'#1.enc#1.pt3 1.`highter'#1.enc#1.pt1 1.`highter'#1.enc#1.pt2 1.`highter'#1.enc#1.pt3

* Import data
use "$adta/Long with outcomes.dta", clear

* Regression loop with output 
 foreach j in 1 {
	local wordcount = 1
	foreach regvar in `outcomes' {
		foreach restrict in "flag_randomized" "flag_randomized_scored_base"  {
			cap drop __*
			local wordtot : word count `outcomes'
			areg `regvar' `loanspec`j'a' if `restrict' == 1 /* & `=cond("`wordcount'" == "`wordtot'", "op18", "`restrict'")' == 1 */, absorb(surveyid) vce(cluster surveyid)
			local inds = e(df_a) + 1
			local obs = e(N)
			sum `regvar' if e(sample) == 1 & post == 1 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_post = string(abs(r(mean)), "%14.`decs'f") 
			}  //end if 
			else {
				local mu_lhs_post = string(r(mean), "%14.`decs'f") 
			}           
			sum `regvar' if e(sample) == 1 & index == 6 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_6 = string(abs(r(mean)), "%14.`decs'f") 
			 }  //end if 
			else {
				local mu_lhs_6 = string(r(mean), "%14.`decs'f") 
			} 
			sum `regvar' if e(sample) == 1 & index == 12 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_12 = string(abs(r(mean)), "%14.`decs'f") 
			}  //end if 
			else {
				local mu_lhs_12 = string(r(mean), "%14.`decs'f") 
			} 
			sum `regvar' if e(sample) == 1 & index == 18 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs_18 = string(abs(r(mean)), "%14.`decs'f") 
			}  //end if 
			else {
				local mu_lhs_18 = string(r(mean), "%14.`decs'f") 
			}        
			sum `regvar' if e(sample) == 1 & index == 1 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs = string(abs(r(mean)), "%14.`decs'f") 
			} 	//end if 
			else {
				local mu_lhs = string(r(mean), "%14.`decs'f") 
			}                     
			if "`regvar'" == "`: word 1 of `outcomes''" {
				local action = "replace"
			}   //end regvar ==
			else {
				local action = "append"
			}       
			#delimit ;                              
			outreg2 using "$outputtables/`filename`j'a'_`restrict'.xls", `action' excel label
				nocons noobs dec(`decs') nor2 addtext(Obs, `obs', Individuals, `inds', 
				Mean Dependent Variable in Extra Step Group at Baseline, `mu_lhs', 
				Mean Dep Var In Extra Step at Post, `mu_lhs_post', 
				Mean Dep Var In Extra Step at 6, `mu_lhs_6', 
				Mean Dep Var In Extra Step at 12, `mu_lhs_12', 
				Mean Dep Var In Extra Step at 18, `mu_lhs_18')  
				slow(8000) nonote noaster;
			#delimit cr;
			sleep 2000 
			cap drop __*
	
			areg `regvar' `loanspec`j'h' if `restrict' == 1 /* & `=cond("`wordcount'" == "`wordtot'", "op18", "`restrict'")' == 1 */ , absorb(surveyid) vce(cluster surveyid)
			local obs = e(N)
			local inds = e(df_a) + 1
			sum `regvar' if e(sample) == 1 & index == 1 & flag_extragroup == 1
			if r(mean) >= -0.001 & r(mean) <= 0.00 {
				local mu_lhs = string(abs(r(mean)), "%14.`decs'f") 
			} 	 //end if 
			else {
				local mu_lhs = string(r(mean), "%14.`decs'f") 
			}  // end else
			if `j' == 1 {
				di "j `j'"
				test 1.`lowter'#1.enc#1.post = 1.`midter'#1.enc#1.post
				local pvalue1_2 = string(r(p), "%14.`decs'f")
				test 1.`midter'#1.enc#1.post = 1.`highter'#1.enc#1.post
				local pvalue2_3 = string(r(p), "%14.`decs'f")
				test 1.`lowter'#1.enc#1.post = 1.`highter'#1.enc#1.post
				local pvalue1_3 = string(r(p), "%14.`decs'f")
				
				if "`regvar'" == "`: word 1 of `outcomes''" {
					local action = "replace"
				} 	 //end regvar == 
				else {
					local action = "append"
				}  	//end else  
				
				#delimit ;                              
				outreg2 using "$outputtables/`filename`j''_`restrict'.xls", `action' excel label 
					nocons noobs dec(`decs') nor2 
					addtext(P-value of 1.`lowter'#1.enc#1.post = 1.`midter'#1.enc#1.post, `pvalue1_2',
							P-value of 1.`midter'#1.enc#1.post = 1.`highter'#1.enc#1.post, `pvalue2_3', 
							P-value of 1.`lowter'#1.enc#1.post = 1.`highter'#1.enc#1.post, `pvalue1_3',
							Obs, `obs', Individuals, `inds', Mean Dependent Variable in Extra Step Group at Baseline, `mu_lhs')  
					slow(8000) nonote noaster;
				#delimit cr;
				sleep 2000 
				//output a blank column
				outreg2 using "$outputtables/`filename`j''_`restrict'.xls", append skip
			}  //end j == 1
			else if `j' == 2 {
				di "j `j'"
				foreach var in "1.`lowter'#1.enc#1.pt1" "1.`lowter'#1.enc#1.pt2" "1.`lowter'#1.enc#1.pt3" "1.`highter'#1.enc#1.pt1" "1.`highter'#1.enc#1.pt2" "1.`highter'#1.enc#1.pt3" {
					foreach group in "1.`lowter'#1.enc#1.pt1" "1.`lowter'#1.enc#1.pt2" "1.`lowter'#1.enc#1.pt3" "1.`highter'#1.enc#1.pt1" "1.`highter'#1.enc#1.pt2" "1.`highter'#1.enc#1.pt3" {
						test "`var'" = "`group'"
						local name = subinstr(subinstr("p`var'`group'", "#","",.), ".","",.)
						local `name' = string(r(p), "%14.`decs'f") 
						di "`name'"
					}  //end foreach group
				}	 //end foreach var
				if "`restrict'" == "flag_randomized" & "`regvar'" == "`: word 1 of `outcomes''"  {
					local action "replace"
				} 
				else {
					local action "append"
				} 
				#delimit ;
				outreg2 using "$outputtables/`filename`j''_`restrict'.xls", `action' 
					keep(1.`lowter'#1.enc#1.pt1 1.`lowter'#1.enc#1.pt2 1.`lowter'#1.enc#1.pt3 
					1.`highter'#1.enc#1.pt1 1.`highter'#1.enc#1.pt2 1.`highter'#1.enc#1.pt3) 
					label nocons noobs dec(`decs') nor2 addtext(
					P-Value for ltca_enc_pt1 = ltca_enc_pt2, `p1ltca1enc1pt11ltca1enc1pt2', 
					P-Value for ltca_enc_pt1 = ltca_enc_pt3, `p1ltca1enc1pt11ltca1enc1pt3',         
					P-Value for ltca_enc_pt2 = ltca_enc_pt3, `p1ltca1enc1pt21ltca1enc1pt3', 
					P-Value for htca_enc_pt1 = htca_enc_pt2, `p1htca1enc1pt11htca1enc1pt2', 
					P-Value for htca_enc_pt1 = htca_enc_pt3, `p1htca1enc1pt11htca1enc1pt3',         
					P-Value for htca_enc_pt2 = htca_enc_pt3, `p1htca1enc1pt21htca1enc1pt3',         
					P-Value for ltca_enc_pt1 = htca_enc_pt1, `p1ltca1enc1pt11htca1enc1pt1',         
					P-Value for ltca_enc_pt2 = htca_enc_pt2, `p1ltca1enc1pt21htca1enc1pt2',
					P-Value for ltca_enc_pt3 = htca_enc_pt3, `p1ltca1enc1pt31htca1enc1pt3', Obs, `obs', 
					Individuals, `inds', Mean Dependent Variable in Extra Step Group at Baseline, `mu_lhs') slow(8000) nonote noaster;
				#delimit cr;
				if "`restrict'" == "flag_randomized_scored_base" {      
					outreg2 using "$outputtables/`filename`j''_`restrict'.xls", append skip
				}  //end of add blank column
			} 	 //end j == 2
		}	//end restrict
		di in red "here"
		local ++wordcount
	} //ends regvar

}

/*******************************************************************************
3. Respose Letter 6
********************************************************************************/

**Tests for Selection Effects into CBL Loans
*A. Filename and table title
local decs 3
local filename1 "Selection Effects Response"

*B. Define the covariate regression spec options and the outcome variables of interest
local outcomes numaccts openrevolvtr
local testcontrols bfico_post fs081_400_post fs081_500_post fs081_600_post

local pana 1.post 1.op18#1.post

local keepa 1.op18#1.post

local i 1 

*C. Import data and create variables related to timing of take up 
use "$adta/Long with outcomes.dta", clear 

*After 30 days
gen open_sd30d_after = ~ open_sd30d if op18 == 1
replace open_sd30d_after = 0 if missing(open_sd30d_after)
tab open_sd30d open_sd30d_after if flag_randomized ==1 & index == 1

*On same day as offer
gen open_sdsame_after = ~ open_sdsame if op18 == 1
replace open_sdsame_after  = 0 if missing(open_sdsame_after)
tab open_sdsame open_sdsame_after if flag_randomized ==1 & index == 1

*From Days 2-30
gen open_sdsame_30 = open_sd30d if op18 == 1
replace open_sdsame_30 = 0 if open_sdsame == 1
replace open_sdsame_30 = 0 if missing(open_sdsame_30)
tab open_sdsame_30 if flag_randomized == 1 & index == 1

keep if flag_randomized == 1 

local t 1
foreach var in `outcomes' {
				
	local controls 			// reset the control local
	local controlss 
	foreach control in `testcontrols' {
		*Standardize each control variable
		*String of locals were attached to each variable name because they should be in the dataset to compare coefficients
		gen `control'_`t' = `control'
		sum `control'_`t' if `=cond("`var'" == "ficoscore08", "flag_matched_scored_base", "flag_matched")' == 1 & !mi(`var') 
		gen `control'stan_`t' = (`control'_`t' - `r(mean)')/`r(sd)' 
		assert mi(`control'_`t') if mi(`control'stan_`t')  
		assert mi(`control'stan_`t') if mi(`control'_`t') 
	    *Generate a missing dummy for each control and replace the missing obs with 0 for both the standardized control var and regular control var 
		gen mi`control'_`t' = (mi(`control'_`t'))
		replace `control'_`t' = 0 if mi(`control'_`t')
		replace `control'stan_`t' = 0 if mi(`control'stan_`t')  
		*create a local of standardized controls and missing dummies for the pdslasso
		local controlss `controlss' `control'stan_`t' mi`control'_`t'
	}

	cap drop __*
	xtset surveyid 
	*run the pdslasso with the standardized control list 
									
	pdslasso `var' `pana' (`controlss'), fe robust 
	local controls `e(xselected)'
	*Remove the stan to use the controls in the regressions
	local controls = subinstr("`controls'", "stan","",.)
	*Include the missing dumy for each selected control 
					
	foreach selected in `controls' {
				if strpos("`selected'", "mi") == 1 {
				continue 
			}
			else {
				local miselected mi`selected'
				local included : list posof "`miselected'" in controls
				cap assert `included' == 0
				if !_rc {	//if the missing dummy is not in the select vars
						local controls `controls' mi`selected'
				}
				else {	//if the missing dummy is already in the selected vars, continue 
						local controls `controls'
				}
			}
	}
						
				
				
	*Mark the sample 
	areg `var'  `pana' `controls' if `=cond("`var'" == "ficoscore08", "flag_matched_scored_base", "flag_matched")' == 1, absorb(surveyid) vce(cluster surveyid)
    tempvar controlsample
	gen `controlsample' = e(sample)  
									
	**With controls
	areg `var'  `pana' `controls' if `=cond("`var'" == "ficoscore08", "flag_matched_scored_base", "flag_matched")' == 1, absorb(surveyid) vce(cluster surveyid)
	loc pval : di %6.2f `r(p)'

	local obs = e(N)
	local inds = e(df_a) + 1
	sum `var' if e(sample) == 1 & index == 1
	local mu_lhs = string(r(mean), "%14.`=cond("`var'" == "ficoscore08", "0", "`decs'")'f") 
	unique surveyid if op18 == 1 & `controlsample' == 1 
	local numopen = r(unique)
				
	outreg2 using "$outputtables/`filename`i''a.xls", keep(`keepa') sortvar(1.op18#1.post) excel label nocons noobs dec(`decs') nor2 slow(8000) nonote noaster addtext(Controls Included?, "Yes", Number of open, `numopen', Obs, `obs', Individuals, `inds', Mean Dependent Variable in CBL Group at Baseline, `mu_lhs') `=cond(`t' == 1,"replace","append")'
					
	local ++t
}


**EOF**

